<script lang="ts" setup>
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { Delete, Plus } from '@element-plus/icons-vue'
import { couponDetail, createDiscountCoupon, getBusinessBlocksList, getProjectPage, updateDiscountCoupon } from '@fl/api/anjutong'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { useRoute, useRouter } from 'vue-router'

const { go, push: routerPush } = useRouter()
const route = useRoute()
const discountCouponId = route.params.id as string
const isCopy = route.params.type === 'copy'
const isEdit = route.params.type === 'edit'

const businessModulesList = ref([])
const detailFormRef = ref()
const initForm = {
    amCouponProjectList: [], // 所选折扣劵项目列表
    couponDescription: '', // 折扣券描述
    couponName: '', // 折扣劵名称
    effectiveDuration: undefined, // 有效时长（领取后多少天内可用）
    endTime: undefined, // 有效期止
    id: undefined, // 折扣劵ID
    plate: '', // 业务板块ID
    plateIds: [],
    plateName: '', // 业务板块名称
    startTime: undefined, // 有效期始
    superimposed: undefined, // 是否叠加（0-否 1-是）
    term: 1, // 有效期（1有效期 2具体多少天）
    timeRange: [], // 有效期范围
    usageTerm: [], // 使用须知
}
const detailForm = ref(cloneDeep(initForm))
const usageTermList = ref([{
    usageTerm: undefined,
}])
const detailRules = {
    couponDescription: [
        { message: '请输入', required: true, trigger: 'blur' },
    ],
    couponName: [
        { message: '请输入', required: true, trigger: 'blur' },
    ],
    effectiveDuration: [
        { trigger: 'blur', validator: (rule: any, value: any, callback: any) => validHolder('blur', detailForm.value.term, 2, value, callback) },
    ],
    plateIds: [
        { message: '请选择', required: true, trigger: 'change' },
    ],
    superimposed: [
        { message: '请选择', required: true, trigger: 'change' },
    ],
    timeRange: [
        { trigger: 'change', validator: (rule: any, value: any, callback: any) => validHolder('change', detailForm.value.term, 1, value, callback) },
    ],
    usageTerm: [
        { message: '请输入', required: true, trigger: 'blur' },
    ],
}

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 70 },
        { field: 'projectName', title: '项目信息', width: 200 },
        { field: 'companyName', title: '开发企业' },
        { field: 'discountCoefficient', slots: { default: 'discountCoefficient' }, title: '折扣', width: 180 },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 80 },
    ],
})

const list = ref([])
const isLoading = ref(false)
const dialogVisible = ref(false)
const updateKey = ref(666)
const dialogInitialState = {
    companyName: undefined, // 开发商
    projectName: undefined, // 项目名称
}
const dialogState = ref(cloneDeep(dialogInitialState))
const dialogcolumns = [
    {
        colProps: {
            span: 12,
        },
        label: '项目名称',
        prop: 'projectName',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 12,
        },
        label: '开发商',
        prop: 'companyName',
        valueType: 'copy',
    },

]

const dialogGridOptions = reactive<VxeGridProps>({
    columns: [
        { type: 'checkbox', width: 50 },
        { title: '序号', type: 'seq', width: 70 },
        { field: 'ghxmmc', title: '项目名称' },
        { field: 'company', title: '开发商' },
        { field: 'address', title: '项目地址' },
        // { field: 'xmdjhstr', title: '项目登记号' },
    ],
})
const loading = ref(false)
const checkedList = ref([])
const checkedIds = ref([])
const dialogInitialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const dialogTablePage = ref(cloneDeep(dialogInitialPage))
const dialogisLoading = ref(false)
const dialogList = ref([])

init()

/**
 * methods start
 */

function init() {
    getBusinessModules()
    if (isEdit || isCopy)
        getDetailData()
}

// 获取业务模块列表
function getBusinessModules() {
    getBusinessBlocksList().then((res) => {
        businessModulesList.value = res
    })
}

// 获取项目分页列表
function getProjectPageList() {
    loading.value = true
    getProjectPage({
        // ...dialogState.value, // 后台要求如何是空字符就不要传入
        companyName: dialogState.value.companyName ? dialogState.value.companyName : undefined,
        pageNum: dialogTablePage.value.currentPage,
        pageSize: dialogTablePage.value.pageSize,
        projectName: dialogState.value.projectName ? dialogState.value.projectName : undefined,
    }).then((res) => {
        loading.value = false
        dialogList.value = res.records
        dialogTablePage.value.total = res.total
    })
}

// 递归获取plateName
function setBusinessModules(list, businessModules) {
    list.forEach((item) => {
        if (businessModules.includes(item.value)) {
            detailForm.value.plateName += `${item.label}/`
        }
        if (item.children) {
            setBusinessModules(item.children, businessModules)
        }
    })
}

function businessModulesChange(vals) {
    detailForm.value.plateName = ''
    setBusinessModules(businessModulesList.value, vals)
}

// 校验调用
function validHolder(type, field, val, value, callback) {
    if (type === 'blur' && field === val && !value) {
        return callback(new Error('请输入'))
    }
    else if (type === 'change' && field === val && !value?.length) {
        return callback(new Error('请选择'))
    }
    else {
        callback()
    }
}

// 禁用二进制中的 'e'、'E'、'-'以及如果是整数integer就阻止小数点的输入
function onKeyPress(event, integer) {
    const key = event.key
    if ((integer && key === '.') || key === 'e' || key === 'E' || key === '-') {
        event.preventDefault()
    }
}

async function addProject() {
    await getProjectPageList()
    dialogVisible.value = true
}

// 新增、编辑提交
function submitForm(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    formEl.validate(async (valid) => {
        if (valid) {
            const { amCouponProjectList, couponDescription, couponName, effectiveDuration, id, plateIds, plateName, superimposed, term, timeRange, startTime, endTime } = detailForm.value
            const usageTerm = usageTermList.value.map(val => val.usageTerm)
            if (!amCouponProjectList.length) {
                ElMessage.error('请选择折扣项目')
                return
            }
            const noDiscount = amCouponProjectList.some(item => !item.discountCoefficient)
            if (noDiscount) {
                ElMessage.error('请选择完善列表中的折扣')
                return
            }
            const params = {
                amCouponProjectList: amCouponProjectList.map(item => ({
                    companyId: item.companyId,
                    companyName: item.company,
                    discountCoefficient: item.discountCoefficient,
                    level: item.level,
                    projectId: item.id || item.projectId,
                    projectName: item.projectName,
                })),
                couponDescription,
                couponName,
                effectiveDuration,
                endTime: undefined,
                id: isEdit ? id : undefined,
                plate: plateIds[0],
                plateLast: plateIds[1],
                plateName: plateName.replace(/\/$/, ''),
                startTime: undefined,
                superimposed,
                usageTerm,
            }
            params.plateName = plateName.replace(/\/$/, '')
            if (term === 1) {
                params.effectiveDuration = undefined
                params.startTime = startTime
                params.endTime = endTime
            }
            if (params.id) {
                updateDiscountCoupon(params).then(() => {
                    ElMessage.success('编辑成功')
                    routerPush({ name: 'discount-manage' })
                })
            }
            else {
                createDiscountCoupon(params).then(() => {
                    ElMessage.success('新增成功')
                    routerPush({ name: 'discount-manage' })
                })
            }
        }
    })
}

// 获取详情数据
function getDetailData() {
    couponDetail({
        id: discountCouponId,
    }).then((res) => {
        const { amCouponProjectList, couponDescription, couponName, effectiveDuration, endTime, id, plate, plateIds, plateName, startTime, superimposed, usageTerm } = res
        let usageTermArr = []
        const reg = /\[.*?\]/
        if (usageTerm && reg.test(usageTerm)) {
            usageTermArr = JSON.parse(usageTerm)
        }
        if (usageTerm && !reg.test(usageTerm)) {
            usageTermArr = [usageTerm]
        }
        usageTermList.value = usageTermArr.map(item => ({ usageTerm: item }))
        detailForm.value = {
            amCouponProjectList: isCopy ? [] : amCouponProjectList,
            couponDescription,
            couponName,
            effectiveDuration,
            endTime,
            id,
            plate,
            plateIds,
            plateName,
            startTime,
            superimposed,
            term: 1,
            timeRange: [],
            usageTerm: [],
        }
        detailForm.value.timeRange = [startTime, endTime]
        list.value = detailForm.value.amCouponProjectList
        if (startTime && startTime)
            detailForm.value.term = 1
        else detailForm.value.term = 2
    })
}

function dialogSearch(values) {
    dialogState.value = values
    getProjectPageList()
}

function dialogFormReset() {
    dialogState.value = cloneDeep(dialogInitialState)
    dialogTablePage.value = cloneDeep(dialogInitialPage)
    getProjectPageList()
}

const dialoghandlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    dialogTablePage.value.currentPage = currentPage
    dialogTablePage.value.pageSize = pageSize
    getProjectPageList()
}

function checkboxChange(checkeds) {
    checkedList.value = checkeds.records.map(item => ({
        address: item.address,
        company: item.company,
        companyId: item.companyId,
        companyName: item.company,
        discountCoefficient: undefined,
        ghxmmc: item.ghxmmc,
        id: item.id,
        level: item.level,
        projectId: item.projectId,
        projectName: item.xmmc,

    }))
    checkedIds.value = checkeds.records.map(item => item.id)
}

function dialogConfirm() {
    let noChecked = false
    list.value.forEach((item) => {
        if (checkedIds.value.includes(item.id)) {
            noChecked = true
        }
    })
    if (noChecked) {
        ElMessage.warning('所选项目中有已添加的项目，请勿重复添加')
        return
    }
    list.value = [...list.value, ...checkedList.value]
    detailForm.value.amCouponProjectList = list.value
    dialogVisible.value = false
}

function delteItem(index) {
    list.value.splice(index, 1)
    detailForm.value.amCouponProjectList = list.value
}

function dialogCancel() {
    checkedList.value = []
    dialogState.value = cloneDeep(dialogInitialState)
    dialogVisible.value = false
}

function handleDialogClose() {
    checkedList.value = []
    dialogState.value = cloneDeep(dialogInitialState)
    dialogTablePage.value = cloneDeep(dialogInitialPage)
    updateKey.value = +new Date()
    dialogVisible.value = false
}

function timeRangeChange(val) {
    console.log(23344, val)
    if (val === 1) {
        detailForm.value.effectiveDuration = undefined
    }
    else {
        detailForm.value.timeRange = []
        detailForm.value.startTime = ''
        detailForm.value.endTime = ''
    }
}

function addUsageTerm() {
    usageTermList.value.push({
        usageTerm: undefined,

    })
}

function removeUsageTerm(index) {
    usageTermList.value.splice(index, 1)
}

function onBlurDiscountCoefficient(row) {
    if(row.discountCoefficient) {
        const val = Number(row.discountCoefficient)
        if(val >= 1) {
            row.discountCoefficient = 0.9999
        }else {
            const val = row.discountCoefficient.toString()
            row.discountCoefficient = Number(val.substring(0,6))
        }
    }
}

function termChange(val) {
    detailForm.value.startTime = `${val[0]} 00:00:00`
    detailForm.value.endTime = `${val[1]} 23:59:59`
}

/**
 * methods end
 */
</script>

<template>
    <div class="activity-coupon-detail">
        <el-button type="info"
                   plain
                   @click="go(-1)"
        >
            返回列表
        </el-button>

        <div class="detail-content">
            <el-form ref="detailFormRef"
                     :model="detailForm"
                     :rules="detailRules"
                     label-width="auto"
                     class="detail-form"
                     label-position="top"
            >
                <div class="base-info">
                    <h3 class="title">
                        基本信息
                    </h3>

                    <div class="form-row">
                        <el-form-item label="折扣劵名称"
                                      prop="couponName"
                        >
                            <el-input v-model.trim="detailForm.couponName"
                                      clearable
                            />
                        </el-form-item>

                        <el-form-item label="业务板块"
                                      prop="plateIds"
                        >
                            <el-cascader v-model="detailForm.plateIds"
                                         :disabled="isEdit"
                                         :options="businessModulesList"
                                         @change="businessModulesChange"
                            />
                        </el-form-item>
                    </div>

                    <div class="form-row">
                        <el-form-item label="叠加情况"
                                      prop="superimposed"
                        >
                            <el-select v-model="detailForm.superimposed"
                                       :disabled="isEdit"
                                       clearable
                                       placeholder="请选择"
                            >
                                <el-option label="不可叠加"
                                           :value="0"
                                />

                                <el-option label="可叠加其他类型的优惠"
                                           :value="1"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item />
                    </div>

                    <div class="form-row">
                        <el-form-item label="折扣券描述"
                                      prop="couponDescription"
                        >
                            <el-input v-model.trim="detailForm.couponDescription"
                                      maxlength="200"

                                      clearable
                                      show-word-limit
                            />
                        </el-form-item>
                    </div>

                    <div class="form-row">
                        <el-form-item label="有效期"
                                      prop="term"
                        >
                            <el-radio-group v-model="detailForm.term"
                                            :disabled="isEdit"
                                            @change="timeRangeChange"
                            >
                                <el-radio :value="1">
                                    <el-form-item class="append"
                                                  prop="timeRange"
                                    >
                                        <el-date-picker v-model="detailForm.timeRange"
                                                        :disabled="isEdit || detailForm.term === 2"
                                                        type="daterange"
                                                        start-placeholder="开始时间"
                                                        end-placeholder="结束时间"
                                                        format="YYYY-MM-DD"
                                                        value-format="YYYY-MM-DD"
                                                        @change="termChange"
                                        />
                                    </el-form-item>
                                </el-radio>

                                <el-radio :value="2"
                                          class="radio-append"
                                          disabled
                                >
                                    <span>领取后</span>

                                    <el-form-item class="append"
                                                  prop="effectiveDuration"
                                    >
                                        <el-input v-model="detailForm.effectiveDuration"
                                                  style="width: 100px"
                                                  type="number"
                                                  :disabled="detailForm.term === 1 || isEdit"
                                                  @keypress="onKeyPress"
                                        />

                                        <span class="append-txt">天内可用</span>
                                    </el-form-item>
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </div>

                    <div class="form-row textarea-form">
                        <el-form-item label="使用须知">
                            <!-- <el-input v-model.trim="detailForm.usageTerm"
                                      clearable
                                      maxlength="200"
                                      show-word-limit
                                      type="textarea"
                            /> -->
                            <div class="explain-list">
                                <div v-for="(item, index) in usageTermList"
                                     :key="index"
                                     class="item"
                                >
                                    <span>{{ index + 1 }}、</span>

                                    <el-input v-model.trim="item.usageTerm"
                                              clearable
                                              maxlength="200"
                                              show-word-limit
                                              placeholder="请输入"
                                    />

                                    <div class="btns">
                                        <el-icon class="add-icon"
                                                 @click="addUsageTerm"
                                        >
                                            <Plus />
                                        </el-icon>

                                        <el-icon v-if="usageTermList.length > 1"
                                                 class="delete-icon"
                                                 @click="removeUsageTerm(index)"
                                        >
                                            <Delete />
                                        </el-icon>
                                    </div>
                                </div>
                            </div>
                        </el-form-item>

                        <div class="el-form-item" />
                    </div>
                </div>

                <div class="other-info">
                    <h3 class="title">
                        折扣项目列表
                    </h3>

                    <ElCard shadow="never">
                        <SearchTable v-bind="gridOptions"
                                     :loading="isLoading"
                                     :data="list"
                        >
                            <template v-if="!isEdit"
                                      #toolbar_buttons
                            >
                                <div class="add-project">
                                    <el-button plain
                                               type="primary"
                                               @click="addProject"
                                    >
                                        添加项目
                                    </el-button>
                                </div>
                            </template>

                            <template #discountCoefficient="{ row }">
                                <el-input-number v-model="row.discountCoefficient"
                                                 :controls="false"
                                                 @blur="onBlurDiscountCoefficient(row)"
                                                 @keypress="onKeyPress"                                                 :disabled="isEdit"
                                                 placeholder="请输入0~1的折扣系数"
                                />
                            </template>

                            <template #operate="{ rowIndex }">
                                <el-button type="primary"
                                           :max="1"
                                           text
                                           @click="delteItem(rowIndex)"
                                >
                                    删除
                                </el-button>
                            </template>
                        </SearchTable>
                    </ElCard>
                </div>
            </el-form>
        </div>

        <div class="footer-btn">
            <el-form-item>
                <el-button type="primary"
                           @click="submitForm(detailFormRef)"
                >
                    保存
                </el-button>

                <el-button @click="go(-1)">
                    取消
                </el-button>
            </el-form-item>
        </div>

        <el-dialog v-model="dialogVisible"
                   :close-on-click-modal="false"
                   :close-on-press-escape="false"
                   title="添加项目"
                   width="1062"
                   modal-class="project-data-dialog"
                   draggable
                   :before-close="handleDialogClose"
        >
            <div v-loading="loading"
                 class="project-list"
            >
                <div class="project-data-list">
                    <SearchForm v-bind="dialogState"
                                :key="updateKey"
                                :columns="dialogcolumns"
                                submit-text="查询"
                                @reset="dialogFormReset"
                                @submit="dialogSearch"
                    />

                    <SearchTable v-bind="dialogGridOptions"
                                 v-model:pager="dialogTablePage"
                                 :loading="dialogisLoading"
                                 :data="dialogList"
                                 @page-change="dialoghandlePageChange"
                                 @checkbox-change="checkboxChange"
                    />
                </div>

                <div class="bottom-btn">
                    <el-button type="primary"
                               @click="dialogConfirm"
                    >
                        确定
                    </el-button>

                    <el-button @click="dialogCancel">
                        取消
                    </el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<style lang="less" scoped>
.activity-coupon-detail {
    .detail-content {
        width: calc(90% - 300px);
        .title {
            font-size: 20px;
            font-weight: 600;
            margin: 30px 0 12px 0;
        }
        .detail-form {
            .form-row {
                display: flex;
                .explain-list {
                    flex: 1;
                    > .item {
                        display: flex;
                        margin-bottom: 12px;
                        .btns {
                            display: flex;
                            align-items: center;
                            .el-icon {
                                cursor: pointer;
                            }
                            .add-icon {
                                color: var(--el-color-primary);
                                margin: 0 6px;
                            }
                        }
                    }
                }
                &.textarea-form {
                    :deep(.el-textarea__inner) {
                        height: 60px;
                        resize: none;
                    }
                }
                .el-form-item {
                    margin-right: 12px;
                    flex: 1;
                }
                .select-project {
                    margin-bottom: 0;
                }
                :deep(.el-cascader) {
                    width: 100%;
                }
            }
            .radio-append {
                :deep(.el-radio__label) {
                    display: flex;
                }
                :deep(.el-form-item__content) {
                    display: flex;
                }
                .append {
                    display: flex;
                    align-items: center;
                    margin-left: 6px;
                    .append-txt {
                        display: block;
                        margin-left: 6px;
                        width: 150px;
                    }
                }
            }
        }
        .add-project {
            display: flex;
            justify-content: flex-end;
            width: 100%;
            padding-right: 12px;
        }
    }
    .footer-btn {
        display: flex;
        justify-content: center;
        margin-top: 30px;
    }
}
.project-list {
    .project-data-list {
        position: relative;
        margin-top: 24px;
        .el-form {
            display: flex;
            justify-content: space-between;
        }
        :deep(.plus-form .plus-form__footer) {
            margin-right: 50px;
        }
    }
    .bottom-btn {
        position: absolute;
        bottom: 30px;
        right: 50%;
        margin-right: -65px;
    }
}
:deep(.project-data-dialog .el-dialog) {
    height: calc(100vh - 90px) !important;
}
:deep(.project-data-dialog .el-dialog__body) {
    overflow: hidden;
    overflow-y: auto;
}
.vxe-grid {
    height: calc(100vh - 365px) !important;
}
.other-info {
    .vxe-grid {
        height: 530px !important;
        overflow-y: auto;
    }
}
</style>
